<?php
class Solvex_Controller_Plugin_ViewSetup extends Zend_Controller_Plugin_Abstract
{
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
		if(!$viewRenderer->view){
			$viewRenderer->initView();
		}
		$view = $viewRenderer->view;
		$path = TEMPLATES_PATH . '/' . Zend_Registry::get('apphost'); 
		if(!is_dir($path) || !is_readable($path)){
			$path = TEMPLATES_PATH . '/default';
		}
		$path .= '/' . Zend_Registry::get('config')->web->design->template . '/views/' . $request->getModuleName();
		$view->addScriptPath($path);
		
		$designConfig = Zend_Registry::get('config')->web->design;
		$view->APP_LANG_RTL = (bool) $designConfig->langRtl;
		$view->APP_STATIC_SERVER = $view->serverUrl() . $view->baseUrl();
		
		$view->headTitle($designConfig->headtitle)->setSeparator($designConfig->headSeparator);
		
		$view->headLink()->appendStylesheet($view->APP_STATIC_SERVER . '/styles/960/reset.css');
		if($view->APP_LANG_RTL){
			$view->headLink()->appendStylesheet($view->APP_STATIC_SERVER . '/styles/960/all-rtl.min.css');
		} else {
			$view->headLink()->appendStylesheet($view->APP_STATIC_SERVER . '/styles/960/all.min.css');
		}

		$db = Zend_Db_Table::getDefaultAdapter();
		$db->setFetchMode(Zend_Db::FETCH_ASSOC);
		$select = $db->select();
		$select->where("site_id = ?", Zend_Registry::get('site')->getId())
			   ->from("navigation");
		$inArray = $db->fetchAll($select);
		if(!function_exists("makeParentChildRelations")){
			function makeParentChildRelations(&$inArray, &$outArray, $currentParentId = 0) {
			    if(!is_array($inArray)) {
			        return;
			    }
			
			    if(!is_array($outArray)) {
			        return;
			    }
			
			    foreach($inArray as $key => $tuple) {
			        if($tuple['parent_id'] == $currentParentId) {
			            $tuple['pages'] = array();
			            makeParentChildRelations($inArray, $tuple['pages'], $tuple['id']);
			            $outArray[] = $tuple;   
			        }
			    }
			}	
		}
		$outArray = array();
		makeParentChildRelations($inArray, $outArray);
		$nav = new Zend_Navigation($outArray);
		$view->navigation($nav); 
	}	
}